import { Button, NavBar, Form, Input, List, Toast } from 'antd-mobile'

import styles from './index.module.scss'
import { useDispatch } from 'react-redux'
import { getCode, userLogin } from '@/store/actions/login'
import { LoginForm } from '@/types/data'
import { useHistory, useLocation } from 'react-router-dom'
import { AxiosError } from 'axios'
import { useRef, useState } from 'react'
import { InputRef } from 'antd-mobile/es/components/input'
import useCountDown from '@/hooks/useCountDown'

const Login = () => {
  const location = useLocation<{from: string}>()
  const { count, start } = useCountDown(10, () => { console.log('倒计时结束'); setSendable(true) })

  // 目前能否发验证码
  const [sendable, setSendable] = useState(true)

  const [form] = Form.useForm()
  const refMobile = useRef<InputRef>(null)
  const dispatch = useDispatch()
  const history = useHistory()
  const onFinish = async (value: LoginForm) => {
    try {
      console.log(1)
      await dispatch(userLogin(value))
      console.log(3)
      // 提示登录成功，跳转页面
      Toast.show({
        content: '登录成功',
        duration: 500,
        afterClose: () => {
          console.log('登录成功', location.state)
          // 检查是否有 需要回跳的地址
          if (location.state) {
            history.push(location.state.from)
          } else {
            // console.log('进入主页')
            history.push('/home')
          }
        }
      })
    } catch (err) {
      console.dir(err)

      // 类型断言
      // err.response.data.message
      const e = err as AxiosError<{message:string}>
      const content = e.response?.data.message || '登录失败'
      // console.dir(e.response?.data.message)
      Toast.show({
        content,
        duration: 800
      })
    }
  }

  // 用户点击获取验证码
  const onGetCode = async () => {
    // 1. 验证手机号的格式，获取它的值
    const hasError = form.getFieldError('mobile').length > 0
    const mobile = form.getFieldValue('mobile')
    if (hasError || !mobile) {
      // 用户的手机号格式不对
      // 手机号文本框自动获得焦点，方便用户修改
      refMobile.current?.focus()
      return
    }
    try {
      // 发短信
      await dispatch(getCode(mobile))
      Toast.show({
        content: '短信已发送',
        duration: 500
      })

      // 启动倒计时
      start()
      setSendable(false) // 不能再发请求
    } catch (err) {
      // 类型断言
      // err.response.data.message
      const e = err as AxiosError<{message:string}>
      const content = e.response?.data.message || '发送失败'
      // console.dir(e.response?.data.message)
      Toast.show({
        content,
        duration: 800
      })
    }
  }

  return (
    <div className={styles.root}>
      <NavBar></NavBar>
      <div className="login-form">
        <h2 className="title">账号登录 {count}</h2>

        <Form onFinish={onFinish} form={form}>
          <Form.Item className="login-item"
            name="mobile"
            rules={[
              { required: true, message: '手机号不能为空' },
              { pattern: /^1\d{10}$/, message: '手机号不合法' }
            ]}
            >
            <Input placeholder="请输入手机号" ref={refMobile}/>
          </Form.Item>
          <List.Item
            className="login-code-extra"
            extra={<span onClick={sendable ? onGetCode : undefined} className="code-extra">
              {sendable ? '发送验证码' : count + '秒之后再发'}
            </span>}
          >
            <Form.Item name="code" className="login-item"
            rules={[
              { required: true, message: '验证码不能为空' },
              { pattern: /^\d{6}$/, message: '验证码不合法' }
            ]}
            >
              <Input placeholder="请输入验证码" autoComplete="off" />
            </Form.Item>
          </List.Item>

          <Form.Item noStyle>
            <Button
              block
              type="submit"
              color="primary"
              className="login-submit"
            >
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
export default Login
